//
//  ComposeViewController.swift
//  sinaweiboFirst
//
//  Created by mac on 16/3/16.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupUI()
        
        //注册通知
        registerNotification()
    }
    
        //发布微博
    @objc private func send() {
    
        print(__FUNCTION__)
        
        //发布图片微博
     
        //1.查看接口文档 
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        
        guard let token = UserAccount.shareAccount.access_token else {
            print("用户未登录或者登陆过期")
            return
        }
        let parameters = ["access_token":token,"status":textView.text]
        
        //如果有图片就发布图片微博
        if pictureSelectedVC.imageList.count != 0 {
        
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //将图片转换成二进制数据
            let imageData = UIImagePNGRepresentation(pictureSelectedVC.imageList.first!)!
            //发布带图片的微博
            HTTPClient.sharedHttpClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                /*
                1.data 表示要上传文件的二进制数据
                2.name 服务器接收的字段名称 pic
                3.fileName 服务器存储的名称 可以随便传 新浪微博防止重复 自己命名
                4.mineType 图片格式
                */
                
                formData.appendPartWithFileData(imageData, name: "pic", fileName: "fuckyou", mimeType: "application/octet-stream")
                
                }, progress: nil, success: { (_, result) -> Void in
                    
                    print(result)
                    SVProgressHUD.showSuccessWithStatus("发布微博成功")
                    
                }, failure: { (_, error) -> Void in
                    
                    print(error)
                    
            })
            
        } else {
        
            //发布文本微博
            HTTPClient.sharedHttpClient.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("发布微博失败")
                    
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发布微博成功")
                self.close()
            }
        }
        

    }
    
    //通知的监听方法中  回调通知对象
    @objc private func keyboardChange(n: NSNotification) {
    
        //打印通知消息
        print(n)
        
        //获取时间
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //字典中如何存储结构体 转换成NSValue类型进行存储  
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

        //更新约束
        let offset = -ScreenH + rect.origin.y
        
        //更改底部视图的 底部约束
        UIView.animateWithDuration(duration) { () -> Void in
            //先收集约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
               
                make.bottom.equalTo(offset)
                
            })
            self.view.layoutIfNeeded()
        }
    }

    //注册通知
    private func registerNotification() {
        //添加键盘的出现和隐藏的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    //图片
    @objc private func selectPicture() {
        print("---------------选择图片-----------")
      
        UIView.animateWithDuration(0.25) { () -> Void in
            //更新控制器视图的高度
            self.pictureSelectedVC.view.snp_updateConstraints { (make) -> Void in
                make.height.equalTo(ScreenH / 3 * 2)
            }
            
            //强制刷新界面
            self.view.layoutIfNeeded()
        }
        
    }
    //表情
    @objc private func selectEmotion() {
        print("--------------选择表情------------")
    }
    //关闭当前页面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
  //添加文本输入视图
    private lazy var textView: UITextView = {
    
        let textV = UITextView()
        textV.backgroundColor = UIColor.blueColor()
        textV.font = UIFont.systemFontOfSize(18)
        textV.textColor = UIColor.darkGrayColor()
        
        //设置代理
        textV.delegate = self
        
        //设置键盘收起方式
        textV.keyboardDismissMode = .OnDrag
        //设置键盘垂直方向可以拽动 可以滑出边界
        textV.alwaysBounceVertical = true
        
        return textV
    }()
    
    //占位文本
    private lazy var placeholderLabel: UILabel = UIFactory.labelFactory("该好好努力复习啦", textColor: UIColor.lightGrayColor(), fontSize: 18)
    
    //底部工具条 默认高度44
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //添加图片
    private lazy var pictureSelectedVC: PictureSelectedViewController = PictureSelectedViewController()
    
}

//类扩展
extension ComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        
        //设置文本的隐藏或者显示
        placeholderLabel.hidden = textView.hasText()
        
        //有文本就可以和右上角"发布"交互
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }

}

//MARK: 设置UI界面
extension ComposeViewController {

    private func setupUI() {
    
        view.backgroundColor = UIColor.whiteColor()
        
//        selectEmotion()
        
        //设置输入视图
        setTextView()
        //设置导航条
        setNavBar()
        //设置底部工具条
        setToolBar()
        //设置图片选择器
        setPictureSelectedVC()
        
        //将toolBar移动到最顶层
        self.view.bringSubviewToFront(toolBar)
    }
    
    
    private func setPictureSelectedVC() {
        //添加视图控制器
        self.addChildViewController(pictureSelectedVC)
        //添加控制器视图
        self.view.addSubview(pictureSelectedVC.view)
        //设置约束
        pictureSelectedVC.view.snp_makeConstraints { (make) -> Void in
            
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
   
    private func setToolBar() {
    
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
        }
        
        var items = [UIBarButtonItem]()
        
        // 添加 UIBarButtonItem 类型的对象到数据源数组中
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
        
            let imageName = item["imageName"]
            let btn = UIFactory.buttonWithImage(imageName, backImageName: nil)
            
            if let actionName = item["actionName"] {
            
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            
            let barItem = UIBarButtonItem(customView: btn)
            items.append(barItem)
            //添加弹簧类型的item FlexibleSpace  
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
 
    private func setTextView() {
        //textView没有placeholder属性
        view.addSubview(textView)
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.left.right.equalTo(self.view)
            
            make.height.equalTo(ScreenH / 3)
        }
        
        //添加自定义的占位文本
        textView.addSubview(placeholderLabel)
        
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView.snp_top).offset(8)
            
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    private func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置导航条的"文案"的自定义  navigationItem.titleView
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = myView
        
        let titleLabel = UIFactory.labelFactory("发布微博", textColor: UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel = UIFactory.labelFactory(UserAccount.shareAccount.name ?? "", textColor: UIColor.darkGrayColor(), fontSize: 14)
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView.snp_top)
            make.centerX.equalTo(myView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(myView.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
        }
        
    }
  
}



